#include "monthsalaryview.h"
#include <QHeaderView>
#include <QDebug>
#include <QDate>
#include <QVariantList>

MonthSalaryView::MonthSalaryView(QWidget *parent) : QWidget(parent),
    adminManager(new AdminManager(this))
{
    setupUI();

    // 连接信号槽
    connect(adminManager, &AdminManager::operationResult, this, &MonthSalaryView::onOperationResult);
}

MonthSalaryView::~MonthSalaryView()
{
    delete adminManager;
    adminManager = nullptr;
}

void MonthSalaryView::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建查询区域
    QWidget *queryWidget = new QWidget(this);
    QHBoxLayout *queryLayout = new QHBoxLayout(queryWidget);

    QLabel *monthLabel = new QLabel("月份:", this);
    monthComboBox = new QComboBox(this);
    monthComboBox->addItem("全部");
    // 添加近12个月的选项
    QDate currentDate = QDate::currentDate();
    for (int i = 0; i < 12; ++i) {
        QDate date = currentDate.addMonths(-i);
        monthComboBox->addItem(date.toString("yyyy-MM"));
    }
    
    QLabel *deptLabel = new QLabel("部门:", this);
    departmentComboBox = new QComboBox(this);
    departmentComboBox->addItem("所有部门", -1);
    
    queryButton = new QPushButton("查询", this);

    queryLayout->addWidget(monthLabel);
    queryLayout->addWidget(monthComboBox);
    queryLayout->addWidget(deptLabel);
    queryLayout->addWidget(departmentComboBox);
    queryLayout->addWidget(queryButton);

    QPushButton *distributeButton = new QPushButton("发放部门工资", this);
    queryLayout->addWidget(distributeButton);

    QPushButton *distributeAllButton = new QPushButton("发放全体工资", this);
    queryLayout->addWidget(distributeAllButton);

    // 连接发放工资按钮
    connect(distributeButton, &QPushButton::clicked, this, &MonthSalaryView::onDistributeSalaryButtonClicked);
    connect(distributeAllButton, &QPushButton::clicked, this, &MonthSalaryView::onDistributeAllSalaryButtonClicked);

    // 创建结果表格
    resultTable = new QTableWidget(this);
    resultTable->setColumnCount(8);
    resultTable->setHorizontalHeaderLabels({"员工ID", "姓名", "职位", "部门", "基本工资", "扣除金额", "实发工资", "发放日期"});
    resultTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 添加到主布局
    mainLayout->addWidget(queryWidget);
    mainLayout->addWidget(resultTable);

    // 设置布局
    setLayout(mainLayout);
    setWindowTitle("薪资管理");

    // 初始化部门下拉框
    initDepartmentComboBox();

    // 连接查询按钮
    connect(queryButton, &QPushButton::clicked, this, &MonthSalaryView::onQueryButtonClicked);
}

void MonthSalaryView::onQueryButtonClicked()
{
    QString month = monthComboBox->currentText();
    int deptId = departmentComboBox->currentData().toInt();

    // 如果选择"全部"，则传入空字符串
    if (month == "全部") {
        month = "";
    }

    // 调用AdminManager的方法按月份和部门查询薪资详情
    QList<QVariantList> results = adminManager->getSalaryDetailsByMonthAndDept(month, deptId);

    // 清空表格
    resultTable->setRowCount(0);

    // 填充表格
    if (!results.isEmpty())
    {
        resultTable->setRowCount(results.size());
        for (int row = 0; row < results.size(); ++row)
        {
            const QVariantList &rowData = results[row];
            for (int col = 0; col < rowData.size() && col < resultTable->columnCount(); ++col)
            {
                QTableWidgetItem *item = new QTableWidgetItem(rowData[col].toString());
                resultTable->setItem(row, col, item);
            }
        }
    }
}

void MonthSalaryView::onOperationResult(bool success, const QString &message)
{
    if (success)
    {
        QMessageBox::information(this, "成功", message);
    }
    else
    {
        QMessageBox::warning(this, "失败", message);
    }
}

void MonthSalaryView::setAdminManager(AdminManager *manager)
{
    adminManager = manager;
    if (adminManager)
    {
        refreshDepartmentList();
    }
}

void MonthSalaryView::refreshDepartmentList()
{
    if (!adminManager) return;

    departmentComboBox->clear();
    departmentComboBox->addItem("所有部门", -1);

    QList<QVariantList> departments = adminManager->getAllDepartments();
    for (const auto &deptVar : departments)
    {
        const QVariantList &deptData = deptVar;
        QVariantHash dept;
        dept.insert("dept_id", deptData[0]);
        dept.insert("dept_name", deptData[1]);
        dept.insert("dept_head_id", deptData[2]);
        dept.insert("emp_name", deptData[3]);
        dept.insert("dept_count", deptData[4]);
        int deptId = dept.value("dept_id").toInt();
        QString deptName = dept.value("dept_name").toString();
        departmentComboBox->addItem(deptName, deptId);
    }
}

void MonthSalaryView::initDepartmentComboBox()
{
    refreshDepartmentList();
}
//发放工资
void MonthSalaryView::onDistributeSalaryButtonClicked()
{
    QString month = monthComboBox->currentText();
    int deptId = departmentComboBox->currentData().toInt();

    // 确保选择了具体月份
    if (month == "全部")
    {
        QMessageBox::warning(this, "选择错误", "请选择具体的月份");
        return;
    }

    // 确认发放工资
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认发放工资",
                                  QString("确定要发放 %1 %2 的工资吗？")
                                  .arg(departmentComboBox->currentText())
                                  .arg(month),
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes)
    {
        // 调用AdminManager发放工资
        bool success = adminManager->distributeSalaryByDept(deptId, month);
        if (success)
        {
            QMessageBox::information(this, "成功", "工资发放成功");
            // 刷新工资数据
            onQueryButtonClicked();
        }
        else
        {
            QMessageBox::warning(this, "失败", "工资发放失败");
        }
    }
}
//发放全体员工的工资
void MonthSalaryView::onDistributeAllSalaryButtonClicked()
{
    QString month = monthComboBox->currentText();

    // 确保选择了具体月份
    if (month == "全部")
    {
        QMessageBox::warning(this, "选择错误", "请选择具体的月份");
        return;
    }

    // 确认发放工资
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认发放工资",
                                  QString("确定要发放全体员工 %1 的工资吗？")
                                  .arg(month),
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes)
    {
        // 调用AdminManager发放全体员工工资
        bool success = adminManager->distributeAllSalaries(month);
        if (success)
        {
            QMessageBox::information(this, "成功", "全体员工工资发放成功");
            // 刷新工资数据
            onQueryButtonClicked();
        }
        else
        {
            QMessageBox::warning(this, "失败", "全体员工工资发放失败");
        }
    }
}
